//
//  UserAccount.swift
//  zyqWeibo
//
//  Created by 张亚琼 on 15/6/27.
//  Copyright © 2015年 张亚琼. All rights reserved.
//

import UIKit

class UserAccount: NSObject,NSCoding {
    // 用于调用access_token
    var access_token: String
    // 类型是NSTimeInterval，接口改了，但是接口文档没改
    var expires_in: NSTimeInterval
    var uid: String
    
    // 过期日期
    var expiresDate: NSDate
    
    // 用户名称，后面加？可以不用在init方法中左初始化
    var name: String?
    // 用户头像地址（大图） 像素是180*180
    var avatar_large: String?
    
    init(dict: [String: AnyObject]) {
        access_token = dict["access_token"] as! String
        expires_in = dict["expires_in"] as! NSTimeInterval
        uid = dict["uid"] as! String
        
        expiresDate = NSDate(timeIntervalSinceNow: expires_in)
    }
    
    // 格式化打印的对象信息
    override var description: String {
        let properties = ["access_token","expires_in","uid","expiresDate","name","avatar_large"]
        
        return "格式化后的UserAccount：\(self.dictionaryWithValuesForKeys(properties))"
        
    }
    
    // 归档路径  类变量
    static let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingPathComponent("account.plist")
    
    /// 将当前对象归档保存至沙盒
    func saveAccount() {
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath)
        print(UserAccount.accountPath)
    }
    // 归档，协议方法
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    /// 加载用户信息，获取到的是之前放入沙盒中的用户token信息
    class func loadAccount() -> UserAccount? {
       
        let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount
        
        if account != nil {
            // 如果是降序，即account的日期大于当前日期，则表示没有过期
            if account!.expiresDate.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                return account
            }
        }
        // 直接返回空，表示已经过期，无法获取用户信息
        return nil
    }
    // 解档方法
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as! String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        uid = aDecoder.decodeObjectForKey("uid") as! String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as! NSDate
        
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    /// 加载用户信息，包括用户名、用户头像
    /// 参数是一个闭包
    func loadUserInfo(finished:(account: UserAccount?,error: NSError?) -> ()){
        // 请求参数数组
        
        // https://api.weibo.com/2/users/show.json?access_token=2.00wfcYsC5gXIBD1b7e0dc541961RGC&uid=2638439632
        let params = ["access_token": access_token,"uid": uid]
        NetworkTool.sharedNetworkTool().GET("2/users/show.json", parameters: params, success: { (_, JSON) -> Void in
            // 请求成功的回调，此时已经获取到用户信息
            let userDict = JSON as! [String:AnyObject]
            self.name = userDict["name"] as? String
            self.avatar_large = userDict["avatar_large"] as? String
            // 获取到了用户名和头像，再保存用户信息
            self.saveAccount()
            
            // 完成回调，把已经加载了用户信息的当前类返回
            finished(account: self, error: nil)
            
            }) { (_, error) -> Void in
                finished(account: nil, error: error)
        }
    }
    
    
    
}
